package com.fire.control.system.module.duty.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.expression.ParseException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.fire.control.system.config.redis.RedisService;
import com.fire.control.system.dto.DutyRequestDTO;
import com.fire.control.system.dto.DutyResultDTO;
import com.fire.control.system.dto.SignResultDTO;
import com.fire.control.system.dto.UserDTO;
import com.fire.control.system.dto.app.AppDeviceGroupVo;
import com.fire.control.system.entity.DeviceGroup;
import com.fire.control.system.entity.Duty;
import com.fire.control.system.entity.DutyLeave;
import com.fire.control.system.entity.DutyResign;
import com.fire.control.system.entity.User;
import com.fire.control.system.module.duty.dao.DutyLeaveMapper;
import com.fire.control.system.module.duty.dao.DutyLeaveRepository;
import com.fire.control.system.module.duty.dao.DutyMapper;
import com.fire.control.system.module.duty.dao.DutyRepository;
import com.fire.control.system.module.duty.dao.DutyResignRepository;
import com.fire.control.system.module.duty.service.IDutyService;
import com.fire.control.system.module.user.dao.UserRepository;
import com.fire.control.system.module.warning.service.AppWarningService;
import com.fire.control.system.statics.ResponseMessage;
import com.fire.control.system.statics.Status_Duty;
import com.fire.control.system.statics.Status_Public;
import com.fire.control.system.support.protocol.comman.ProtocolSelector;
import com.fire.control.system.support.protocol.comman.ResponseJsonProtocol;
import com.fire.control.system.support.protocol.comman.ResponseProtocol;
import com.fire.control.system.support.protocol.duty.DutyRequestProtocol;
import com.fire.control.system.support.protocol.duty.LeaveDutyRequestProtocol;
import com.fire.control.system.support.protocol.duty.SignRequestProtocol;
import com.fire.control.system.support.util.ResultPageUtil;
import com.fire.control.system.support.util.TimeUtil;
import com.fire.control.system.support.util.XdaoDate;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.StringUtil;

/**
 * @author liuxincheng
 * @ClassName: DutyServiceImpl
 * @Description: TODO(值班服务实现)
 * @date 2017年6月1日 下午3:06:33
 */
@Service
@Transactional
public class DutyServiceImpl implements IDutyService {

	@Autowired
	private ProtocolSelector protocolSelector;

	@Autowired
	private UserRepository userRepository;

	@Autowired
	private DutyRepository dutyRepository;

	@Autowired
	private DutyMapper dutyMapper;
	@Autowired
	private DutyLeaveMapper dutyLeaveMapper;
	@Autowired
	private DutyResignRepository dutyResignRepository;

	@Autowired
	private DutyLeaveRepository dutyLeaveRepository;

	@Autowired
	private TimeUtil timeUtil;

	@Autowired
	private ResultPageUtil resultPageUtil;
	@Autowired
	private AppWarningService appWarningService;

	@Autowired
	private RedisService redisService;

	/**
	 * @Title: dutyDetection
	 * @Description: TODO(定时更新当日值班缺勤的人员数据)
	 * @author wanbo
	 * @date 2017年6月30日 下午6:56:39
	 */
	public void updateTodayDutyNoAttendance() {
		dutyMapper.updateTodayDutyNoAttendance();
	}

	/**
	 * <p>
	 * Title: jumpToSignPage
	 * </p>
	 * <p>
	 * Description: 跳转到签到页面
	 * </p>
	 * 
	 * @param requestProtocol
	 * @return
	 * @see com.fire.control.system.IDutyService.service.ISignService#jumpToSignPage(com.fire.control.system.support.protocol.duty.DutyRequestProtocol)
	 */
	@Override
	public ResponseProtocol jumpToSignPage(SignRequestProtocol requestProtocol, UserDTO user) {
		ResponseJsonProtocol response = new ResponseJsonProtocol();
		User u = userRepository.findOne(user.getUserId());
		String signScope = u.getCompany().getSignErrorScop();
		List<AppDeviceGroupVo> deviceGroupList = new ArrayList<AppDeviceGroupVo>();
		Collection<DeviceGroup> deviceGroup = u.getDeviceGroups();
		Map<String, Object> returnMap = new HashMap<String, Object>();
		for (DeviceGroup dg : deviceGroup) {
			AppDeviceGroupVo vo = new AppDeviceGroupVo();
			vo.setAppDeviceGroupVo(dg);
			deviceGroupList.add(vo);
		}
		if (deviceGroupList == null || deviceGroupList.isEmpty()) {
			ResponseMessage.CODE_204.messageToProtocol(response);
		} else {
			returnMap.put("deviceGroupList", deviceGroupList);
			returnMap.put("signScope", signScope);
			response.setData(returnMap);
			ResponseMessage.CODE_200.messageToProtocol(response).setMessage("数据返回成功!");
		}
		return response;
	}

	/**
	 * <p>
	 * Title: confirmSign
	 * </p>
	 * <p>
	 * Description: 签到确定
	 * </p>
	 * 
	 * @param requestProtocol
	 * @param user
	 * @return
	 * @see com.fire.control.system.module.duty.service.IDutyService#confirmSign(com.fire.control.system.support.protocol.duty.SignRequestProtocol,
	 *      com.fire.control.system.dto.UserDTO)
	 */
	@Override
	public ResponseProtocol confirmSign(SignRequestProtocol requestProtocol, UserDTO user) {
		// TODO Auto-generated method stub
		ResponseJsonProtocol response = new ResponseJsonProtocol();
		String userId = user.getUserId();
		Duty duty = new Duty();
		duty.setDutyStatus(Status_Duty.sign.toString());
		duty.setUserId(userId);
		duty.setSignAddress(requestProtocol.getSignAdress());
		int i = dutyMapper.sign(duty);

		if (i > 0) {
			ResponseMessage.CODE_200.messageToProtocol(response).setMessage("签到成功!");
		} else {
			ResponseMessage.CODE_400.messageToProtocol(response).setMessage("签到失败!");
		}
		return response;
	}

	/**
	 * <p>
	 * Title: confirmFlushData
	 * </p>
	 * <p>
	 * Description: 签到刷新数据
	 * </p>
	 * 
	 * @param requestProtocol
	 * @return
	 * @see com.fire.control.system.IDutyService.service.ISignService#confirmFlushData(com.fire.control.system.support.protocol.duty.DutyRequestProtocol)
	 */
	@Override
	public ResponseProtocol signDataFetch(SignRequestProtocol requestProtocol, UserDTO user) {
		ResponseJsonProtocol response = new ResponseJsonProtocol();
		String userId = user.getUserId();

		int year = requestProtocol.getYear();
		int month = requestProtocol.getMonth();
		// 获取当月的打卡记录
		List<Duty> dutyList = dutyMapper.getDutyList(userId, year, month);

		Collection<SignResultDTO> signResultList = new ArrayList<SignResultDTO>();

		SignResultDTO signResultDTO = null;
		for (Duty d : dutyList) {
			signResultDTO = new SignResultDTO();
			signResultDTO.setId(d.getId());
			signResultDTO.setDutyDate(d.getDutyDate());
			signResultDTO.setDutyStatus(d.getDutyStatus());
			signResultList.add(signResultDTO);
		}
		if (!signResultList.isEmpty() && signResultList.size() > 1) {
			response.setData(signResultList);
			ResponseMessage.CODE_200.messageToProtocol(response).setMessage("数据获取成功!");
		} else {
			ResponseMessage.CODE_400.messageToProtocol(response).setMessage("数据获取失败!");
		}
		return response;
	}

	/**
	 * <p>
	 * Title: patchSignIn
	 * </p>
	 * <p>
	 * Description: 补签到
	 * </p>
	 * 
	 * @param requestProtocol
	 * @return
	 * @see com.fire.control.system.IDutyService.service.ISignService#patchSignIn(com.fire.control.system.support.protocol.duty.DutyRequestProtocol)
	 */
	@Override
	public ResponseProtocol patchSignIn(SignRequestProtocol requestProtocol, UserDTO user) {
		// TODO Auto-generated method stub
		ResponseProtocol response = protocolSelector.choose(requestProtocol);

		// 获取补签到时间
		List<Date> resignDates = requestProtocol.getResignDates();

		// 获得补签内容
		String resignContent = requestProtocol.getResignContent();

		// 补签地址
		String signAddress = requestProtocol.getSignAdress();
		// 补签到集合
		Collection<DutyResign> dutyResigns = new ArrayList<DutyResign>();

		DutyResign dr = null;
		for (Date d : resignDates) {
			dr = new DutyResign();
			dr.setResignContent(resignContent);
			dr.setResignDate(d);
			dr.setUserId(user.getUserId());
			// dr.setAuditUserId(auditUserId);

			dutyResigns.add(dr);
		}

		// 保存补签类容
		List<DutyResign> returnDutyResign = dutyResignRepository.save(dutyResigns);

		Duty duty = null;
		Collection<Duty> dutys = new ArrayList<Duty>();

		if (!returnDutyResign.isEmpty() && returnDutyResign.size() > 0) {

			for (DutyResign d : returnDutyResign) {
				duty = new Duty();

				duty.setSignTime(d.getResignDate());
				duty.setStatus(true);
				duty.setDutyStatus(Status_Duty.resign_audit.toString());
				duty.setSignAddress(signAddress);
				duty.setCompanyId(user.getCompany().getId());
				duty.setUserId(user.getUserId());
				duty.setUpdateTime(new XdaoDate());

				dutys.add(duty);
			}

			List<Duty> returnDuty = dutyRepository.save(dutys);

			if (!returnDuty.isEmpty() && returnDuty.size() > 0) {
				ResponseMessage.CODE_200.messageToProtocol(response);
				response.setDate(new XdaoDate());
				response.setData(returnDuty);
			} else {
				ResponseMessage.CODE_400.messageToProtocol(response).setMessage("补签失败!");
				response.setDate(new XdaoDate());
				response.setData(null);
			}
		} else {
			ResponseMessage.CODE_400.messageToProtocol(response).setMessage("补签失败!");
			response.setDate(new XdaoDate());
		}
		return response;
	}

	/**
	 * @author liuxincheng
	 * @Title: dutySheet
	 * @Description: TODO(值班表)
	 * @param @param
	 *            requestProtocol
	 * @param @return
	 *            设定文件
	 * @return ResponseProtocol 返回类型
	 * @throws null
	 */
	@Override
	public ResponseProtocol dutySheet(SignRequestProtocol requestProtocol, UserDTO user) {
		// TODO Auto-generated method stub
		ResponseProtocol response = protocolSelector.choose(requestProtocol);
		boolean flag = false;
		Map<String, Object> map = new HashMap<String, Object>();

		int year = requestProtocol.getYear();
		int month = requestProtocol.getMonth();

		// 查询值班数据
		List<Duty> dutyList = dutyMapper.getDutyList(user.getUserId(), year, month);

		if (!dutyList.isEmpty() && dutyList.size() > 0) {
			map.put("dutyList", dutyList);
			flag = true;
		} else {
			flag = false;
		}

		if (flag) {
			ResponseMessage.CODE_200.messageToProtocol(response);
			response.setDate(new XdaoDate());
			response.setData(map);
		} else {
			ResponseMessage.CODE_400.messageToProtocol(response).setMessage("数据返回失败!");
			response.setDate(new XdaoDate());
			response.setData(null);
		}
		return response;
	}

	/**
	 * <p>
	 * Title: dutyLeave
	 * </p>
	 * <p>
	 * Description: 请假
	 * </p>
	 * 
	 * @param requestProtocol
	 * @return
	 * @see com.fire.control.system.module.duty.service.IDutyService#dutyLeave(com.fire.control.system.support.protocol.duty.DutyRequestProtocol)
	 */
	@Override
	public ResponseProtocol dutyLeave(DutyRequestProtocol requestProtocol) {
		// TODO Auto-generated method stub
		ResponseProtocol response = protocolSelector.choose(requestProtocol);

		DutyLeave dutyLeave = requestProtocol.getDutyLeave();

		int result = dutyMapper.saveDutyLeave(dutyLeave);

		if (!Integer.valueOf(result).equals(null)) {
			ResponseMessage.CODE_200.messageToProtocol(response);
			response.setDate(new XdaoDate());
			response.setData(result);
		} else {
			ResponseMessage.CODE_400.messageToProtocol(response).setMessage("请假失败!");
			response.setDate(new XdaoDate());
			response.setData(null);
		}
		return response;
	}

	/**
	 * <p>
	 * Title: signInList
	 * </p>
	 * <p>
	 * Description: 签到数据获取
	 * </p>
	 * 
	 * @param requestProtocol
	 * @return
	 * @see com.fire.control.system.module.duty.service.IDutyService#signInList(com.fire.control.system.support.protocol.duty.DutyRequestProtocol)
	 */
	@Override
	public ResponseProtocol signInList(DutyRequestProtocol requestProtocol, Pageable p) {
		// TODO Auto-generated method stub
		ResponseProtocol response = protocolSelector.choose(requestProtocol);

		Status_Duty dutyStatu = requestProtocol.getDutyStatu();
		String userId = requestProtocol.getUserId();

		Page<Duty> dutySignList = dutyRepository.findAll(new Specification<Duty>() {

			@Override
			public Predicate toPredicate(Root<Duty> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				// TODO Auto-generated method stub
				List<Predicate> predicateList = new ArrayList<Predicate>();

				if (!dutyStatu.equals(null)) {
					predicateList.add(cb.equal(root.get("dutyStatus").as(Status_Duty.class), dutyStatu));
				}

				if (!StringUtil.isEmpty(userId)) {
					predicateList.add(cb.equal(root.get("userId").as(String.class), userId));
				}
				query.orderBy(cb.desc(root.get("id").as(String.class)));

				Predicate[] predicates = new Predicate[predicateList.size()];
				predicates = predicateList.toArray(predicates);
				query.where(cb.and(predicates));
				return cb.and(predicates);
			}

		}, p);

		if (dutySignList.hasContent() && dutySignList.getSize() > 0) {
			ResponseMessage.CODE_200.messageToProtocol(response).setMessage("数据获取成功!");
			response.setData(dutySignList);
		} else {
			ResponseMessage.CODE_400.messageToProtocol(response).setMessage("数据获取失败!");
		}
		return response;
	}

	/************************************** web端接口 *********************************************/

	/**
	 * <p>
	 * Title: jumpToDutySheetPage
	 * </p>
	 * <p>
	 * Description: 跳转到值班列表
	 * </p>
	 * 
	 * @param requestProtocol
	 * @return
	 * @see com.fire.control.system.module.duty.service.IDutyService#jumpToDutySheetPage(com.fire.control.system.support.protocol.duty.DutyRequestProtocol)
	 */
	@Override
	public ResponseProtocol jumpToDutySheetPage(DutyRequestProtocol requestProtocol) {
		// TODO Auto-generated method stub
		ResponseProtocol response = protocolSelector.choose(requestProtocol);
		// DutyRequestDTO requestDTO = requestProtocol.getRequestDTO();

		// List<Company> companyList = company
		return null;
	}

	/**
	 * <p>
	 * Title: getDutySheetByCondition
	 * </p>
	 * <p>
	 * Description: 根据条件获得值班列表
	 * </p>
	 * 
	 * @param requestProtocol
	 * @param p
	 * @return
	 * @see com.fire.control.system.module.duty.service.IDutyService#getDutySheetByCondition(com.fire.control.system.support.protocol.duty.DutyRequestProtocol,
	 *      org.springframework.data.domain.Pageable)
	 */
	@SuppressWarnings("static-access")
	@Override
	public ResponseProtocol getDutySheetByCondition(LeaveDutyRequestProtocol requestProtocol) {
		// TODO Auto-generated method stub
		Date date = null;
		String currentDate = "";
		ResponseProtocol response = protocolSelector.choose(requestProtocol);

		DutyRequestDTO requestDTO = requestProtocol.getRequestDTO();

		if (requestProtocol.getRequestDTO() == null) {
			date = new Date();
			try {
				requestDTO = new DutyRequestDTO();
				currentDate = timeUtil.formatTimeUK(date.toString(), "yyyy-MM");
				requestDTO.setDate(currentDate);
			} catch (java.text.ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {
			try {
				date = requestDTO.getDutyDate();
				Date newDate = timeUtil.parse(date.toString(), "yyyy-MM");
				requestDTO.setDate(newDate.toString());
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (java.text.ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		List<Duty> dutyList = dutyMapper.getDutySheetByCondition(requestProtocol);
		List<User> userList = userRepository.findAll();

		Collection<Duty> dutyCollection = null;

		List<DutyResultDTO> duresultDTOList = new ArrayList<DutyResultDTO>();
		DutyResultDTO dutyResultDTO = null;

		for (User u : userList) {
			dutyResultDTO = new DutyResultDTO();
			dutyCollection = new ArrayList<Duty>();

			for (Duty d : dutyList) {
				if (d.getUserId().equals(u.getId())) {
					dutyCollection.add(d);
				}
			}

			if (!dutyCollection.isEmpty() && dutyCollection.size() > 0) {
				dutyResultDTO.setDutyList(dutyCollection);
				dutyResultDTO.setU(u);
				duresultDTOList.add(dutyResultDTO);
			}
		}
		Map<String, Object> returnPage = resultPageUtil.resultPage(new PageInfo<DutyResultDTO>(duresultDTOList),
				duresultDTOList);
		if (!returnPage.isEmpty() && !returnPage.equals(null)) {
			response.setData(returnPage);
			ResponseMessage.CODE_200.messageToProtocol(response).setMessage("数据获取成功!");
		} else {
			ResponseMessage.CODE_400.messageToProtocol(response).setMessage("数据获取失败!");
		}

		return response;
	}

	/**
	 * <p>
	 * Title: jumpToUpdatePage
	 * </p>
	 * <p>
	 * Description: 跳到修改/添加值班信息页面
	 * </p>
	 * 
	 * @param requestProtocol
	 * @return
	 * @see com.fire.control.system.module.duty.service.IDutyService#jumpToUpdatePage(com.fire.control.system.support.protocol.duty.DutyRequestProtocol)
	 */
	@Override
	public ResponseProtocol jumpToUpdatePage(DutyRequestProtocol requestProtocol,UserDTO user) {
		// TODO Auto-generated method stub
		ResponseProtocol response = protocolSelector.choose(requestProtocol);

		Map<String, Object> returnMap = new HashMap<String, Object>();
		
		List<Duty> dutyList = dutyMapper.getDutySheetByUserId(user.getUserId());

		User u = dutyMapper.getUserByUserId(user.getUserId());
		if (!dutyList.isEmpty() && dutyList.size() > 0) {
			// 如果有用户信息，则跳到修改信息页面
			returnMap.put("userName", u.getName());
			returnMap.put("dutyList", dutyList);
		}

		if (!returnMap.isEmpty() && !returnMap.equals(null)) {
			response.setData(returnMap);
			ResponseMessage.CODE_200.messageToProtocol(response);
		} else {
			ResponseMessage.CODE_DEFINED.messageToProtocol(response);
		}
		return response;
	}

	/**
	 * <p>
	 * Title: addDutyInfo
	 * </p>
	 * <p>
	 * Description: 添加值班人员信息
	 * </p>
	 * 
	 * @param requestProtocol
	 * @return
	 * @see com.fire.control.system.module.duty.service.IDutyService#addDutyInfo(com.fire.control.system.support.protocol.duty.DutyRequestProtocol)
	 */
	@Override
	public ResponseProtocol addDutyInfo(DutyRequestProtocol requestProtocol) {
		// TODO Auto-generated method stub
		ResponseProtocol response = protocolSelector.choose(requestProtocol);

		String[] dutyDates = requestProtocol.getDutyDates();

		String userName = requestProtocol.getUserName();

		User u = dutyMapper.getUserByName(userName);

		String company_id = dutyMapper.getCompanyIdByUserId(u.getId());

		Collection<Duty> dutys = new ArrayList<Duty>();

		Duty duty = null;
		for (String dutyDate : dutyDates) {
			duty = new Duty();

			duty.setId(UUID.randomUUID().toString());
			duty.setCreateTime(new XdaoDate());
			duty.setStatus(false);

			duty.setUserId(u.getId());

			duty.setCompanyId(company_id);

			try {
				duty.setDutyDate(timeUtil.parse(dutyDate, "yyyy-MM-dd HH:mm:ss"));
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (java.text.ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			dutys.add(duty);
		}

		List<Duty> returnDutys = dutyRepository.save(dutys);

		if (returnDutys.size() > 0 && !returnDutys.equals(null)) {
			ResponseMessage.CODE_200.messageToProtocol(response);
			response.setData("值班数据添加成功!");
		} else {
			ResponseMessage.CODE_401.messageToProtocol(response);
		}
		return response;
	}

	/**
	 * <p>
	 * Title: updateDutyInfomation
	 * </p>
	 * <p>
	 * Description: 修改值班信息
	 * </p>
	 * 
	 * @param requestProtocol
	 * @return
	 * @see com.fire.control.system.module.duty.service.IDutyService#updateDutyInfomation(com.fire.control.system.support.protocol.duty.DutyRequestProtocol)
	 */
	@Override
	public ResponseProtocol updateDutyInfomation(DutyRequestProtocol requestProtocol) {
		// TODO Auto-generated method stub
		ResponseProtocol response = protocolSelector.choose(requestProtocol);

		String[] dutyDate = requestProtocol.getDutyDates();

		String userName = requestProtocol.getUserName();

		User u = dutyMapper.getUserByName(userName);

		String company_id = dutyMapper.getCompanyIdByUserId(u.getId());

		// 获得该用户已经值班的时间信息
		List<Object> dutyDates = new ArrayList<Object>();
		List<Duty> dutyList = dutyMapper.getDutySheetByUserId(u.getId());

		// 排除已经值班的时间
		int n = 0;
		if (!dutyList.equals(null) && dutyList.size() > 0) {
			for (Duty d : dutyList) {
				n = 0;
				String newDate = timeUtil.formatTime("yyyy-MM-dd HH:mm:ss", d.getDutyDate());
				for (String date : dutyDate) {
					if (!newDate.equals(date)) {
						if (n == dutyDate.length) {
							dutyDates.add(date);
						}
						n++;
					}
				}
			}
		} else {
			for (String date : dutyDate) {
				dutyDates.add(date);
			}
		}

		Collection<Duty> dutys = new ArrayList<Duty>();

		Duty duty = null;

		for (Object o : dutyDates) {
			duty = new Duty();

			duty.setCompanyId(company_id);

			duty.setId(UUID.randomUUID().toString());
			duty.setCreateTime(new XdaoDate());
			duty.setStatus(false);

			duty.setUserId(u.getId());

			duty.setCompanyId(company_id);

			try {
				duty.setDutyDate(timeUtil.parse(String.valueOf(o), "yyyy-MM-dd HH:mm:ss"));
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (java.text.ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			dutys.add(duty);
		}

		List<Duty> returnDutys = dutyRepository.save(dutys);

		if (returnDutys.size() > 0 && !returnDutys.equals(null)) {
			ResponseMessage.CODE_200.messageToProtocol(response).setMessage("值班数据修改成功!");
			;
		} else {
			ResponseMessage.CODE_401.messageToProtocol(response).setMessage("值班数据修改失败!");
		}
		return response;
	}

	/**
	 * <p>
	 * Title: deleteDutyInfomation
	 * </p>
	 * <p>
	 * Description: 删除值班信息
	 * </p>
	 * 
	 * @param requestProtocol
	 * @return
	 * @see com.fire.control.system.module.duty.service.IDutyService#deleteDutyInfomation(com.fire.control.system.support.protocol.duty.DutyRequestProtocol)
	 */
	@Override
	public ResponseProtocol deleteDutyInfomation(DutyRequestProtocol requestProtocol) {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * <p>
	 * Title: addDutyLeave
	 * </p>
	 * <p>
	 * Description: APP端-------添加请假功能
	 * </p>
	 * 
	 * @param leaveDutyRequestProtocol
	 * @param user
	 * @return
	 * @see com.fire.control.system.module.duty.service.IDutyService#addDutyLeave(com.fire.control.system.support.protocol.duty.LeaveDutyRequestProtocol,
	 *      com.fire.control.system.dto.UserDTO)
	 */
	@Override
	public ResponseProtocol addDutyLeave(LeaveDutyRequestProtocol leaveDutyRequestProtocol, UserDTO user) {
		// TODO Auto-generated method stub
		ResponseProtocol response = protocolSelector.choose(leaveDutyRequestProtocol);
		String dutyLeaveContent = leaveDutyRequestProtocol.getDutyLeaveContent();
		try {
			Date startTime = timeUtil.parse(leaveDutyRequestProtocol.getStartTime(), "yyyy-MM-dd HH:mm");
			Date endTime = timeUtil.parse(leaveDutyRequestProtocol.getEndTime(), "yyyy-MM-dd HH:mm");

			DutyLeave dutyLeave = new DutyLeave();
			dutyLeave.setUserId(user.getUserId());
			dutyLeave.setStartTime(startTime);
			dutyLeave.setCreateTime(new Date());
			dutyLeave.setUpdateTime(new Date());
			dutyLeave.setLeaveContent(dutyLeaveContent);
			dutyLeave.setEndTime(endTime);
			dutyLeave.setAuditStatus(Status_Public.wait.name());
			dutyLeaveRepository.save(dutyLeave);
			// 修改值班状态为 请假审核中
			leaveDutyRequestProtocol.setUserId(user.getUserId());
			leaveDutyRequestProtocol.setStartTime(timeUtil.formatTime("yyyy-MM-dd HH:mm",startTime));
			leaveDutyRequestProtocol.setEndTime(timeUtil.formatTime("yyyy-MM-dd HH:mm",endTime));
			leaveDutyRequestProtocol.setStatus("1");

			List<Duty> listDuty = dutyMapper.getDutySheetByCondition(leaveDutyRequestProtocol);

			for (Duty duty : listDuty) {
				duty.setDutyStatus(Status_Duty.rest_audit.toString());
			}
			List<Duty> returnDuty = dutyRepository.save(listDuty);

			if (!returnDuty.isEmpty() && returnDuty.size() > 0) {
				response.setData(returnDuty);
				ResponseMessage.CODE_200.messageToProtocol(response).setMessage("请假申请成功!");
			}else{
				ResponseMessage.CODE_400.messageToProtocol(response).setMessage("请假成功但数据返回异常!");
			}
			return response;
		} catch (Exception e) {
			e.printStackTrace();
			ResponseMessage.CODE_400.messageToProtocol(response).setMessage("请假申请失败");
			return response;
		}
	}

	/**
	 * <p>
	 * Title: updateDutyLeaveStatus
	 * </p>
	 * <p>
	 * Description: WEB端-------->修改请假申请状态
	 * </p>
	 * 
	 * @param leaveDutyRequestProtocol
	 * @return
	 * @see com.fire.control.system.module.duty.service.IDutyService#updateDutyLeaveStatus(com.fire.control.system.support.protocol.duty.LeaveDutyRequestProtocol)
	 */
	@Override
	public ResponseProtocol updateDutyLeaveStatus(LeaveDutyRequestProtocol leaveDutyRequestProtocol) {
		ResponseProtocol response = protocolSelector.choose(leaveDutyRequestProtocol);
		try {
			DutyLeave paramDutyLeave = leaveDutyRequestProtocol.getDutyLeave();
			if (paramDutyLeave == null) {
				return ResponseMessage.CODE_400.messageToProtocol(response);
			}
			DutyLeave dutyLeave = dutyLeaveRepository.findOne(paramDutyLeave.getId());

			dutyLeave.setAuditStatus(Status_Public.wait.name());
			if (StringUtils.equals(leaveDutyRequestProtocol.getReviewStatus(), "yes")) {
				dutyLeave.setAuditStatus(Status_Public.yes.name());
			}
			if (StringUtils.equals(leaveDutyRequestProtocol.getReviewStatus(), "no")) {
				dutyLeave.setAuditStatus(Status_Public.no.name());
			}
			DutyLeave dLeave = dutyLeaveRepository.save(dutyLeave);

			if (dutyLeave != null) {
				Date startTime = dLeave.getStartTime();
				Date endTime = dLeave.getEndTime();
				String userId = dLeave.getUserId();
				SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
				String strStartTime = sf.format(startTime);
				String strEndTime = sf.format(endTime);
				sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

				leaveDutyRequestProtocol.setUserId(userId);
				leaveDutyRequestProtocol.setStartTime(sf.parse(strStartTime + " " + "00:00:00").toString());
				leaveDutyRequestProtocol.setEndTime(sf.parse(strEndTime + " " + "23:59:59").toString());
				leaveDutyRequestProtocol.setStatus("1");

				List<Duty> listDuty = dutyMapper.getDutySheetByCondition(leaveDutyRequestProtocol);
				for (Duty duty : listDuty) {
					duty.setDutyStatus(Status_Duty.leave.toString());

				}
				dutyRepository.save(listDuty);

			}
			return response;
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseMessage.CODE_400.messageToProtocol(response);
		}
	}

	/**
	 * <p>
	 * Title: updateDutyLeaveStatusByIds
	 * </p>
	 * <p>
	 * Description: 修改请假状态
	 * </p>
	 * 
	 * @param leaveDutyRequestProtocol
	 * @return
	 * @see com.fire.control.system.module.duty.service.IDutyService#updateDutyLeaveStatusByIds(com.fire.control.system.support.protocol.duty.LeaveDutyRequestProtocol)
	 */
	@Override
	public ResponseProtocol updateDutyLeaveStatusByIds(LeaveDutyRequestProtocol leaveDutyRequestProtocol) {
		ResponseProtocol response = protocolSelector.choose(leaveDutyRequestProtocol);
		try {
			String[] ids = leaveDutyRequestProtocol.getIds();
			if (ids == null) {
				return ResponseMessage.CODE_400.messageToProtocol(response);
			}
			List<String> listIds = Arrays.asList(ids);
			List<DutyLeave> listDutyLeave = dutyLeaveRepository.findAll(listIds);

			for (DutyLeave dutyLeave : listDutyLeave) {
				dutyLeave.setAuditStatus(Status_Public.wait.name());
				if (StringUtils.equals(leaveDutyRequestProtocol.getReviewStatus(), "yes")) {
					dutyLeave.setAuditStatus(Status_Public.yes.name());
				}
				if (StringUtils.equals(leaveDutyRequestProtocol.getReviewStatus(), "no")) {
					dutyLeave.setAuditStatus(Status_Public.no.name());
				}
			}
			List<DutyLeave> dLeave = dutyLeaveRepository.save(listDutyLeave);
			for (DutyLeave dutyLeave : dLeave) {
				if (dutyLeave != null) {
					Date startTime = dutyLeave.getStartTime();
					Date endTime = dutyLeave.getEndTime();
					String userId = dutyLeave.getUserId();
					SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
					String strStartTime = sf.format(startTime);
					String strEndTime = sf.format(endTime);
					sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

					leaveDutyRequestProtocol.setUserId(userId);
					leaveDutyRequestProtocol.setStartTime(sf.parse(strStartTime + " " + "00:00:00").toString());
					leaveDutyRequestProtocol.setEndTime(sf.parse(strEndTime + " " + "23:59:59").toString());
					leaveDutyRequestProtocol.setStatus("1");

					List<Duty> listDuty = dutyMapper.getDutySheetByCondition(leaveDutyRequestProtocol);
					for (Duty duty : listDuty) {
						duty.setDutyStatus(Status_Duty.leave.toString());
					}
					dutyRepository.save(listDuty);
				}
			}
			return response;
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseMessage.CODE_400.messageToProtocol(response);
		}
	}

	@Override
	public ResponseProtocol findDutyLeaveList(LeaveDutyRequestProtocol leaveDutyRequestProtocol) {
		ResponseProtocol response = protocolSelector.choose(leaveDutyRequestProtocol);
		try {
			PageHelper.startPage(leaveDutyRequestProtocol.getPageNum(), leaveDutyRequestProtocol.getPageSize());
			List<Map<String, Object>> lists = dutyLeaveMapper.findDutyList(leaveDutyRequestProtocol);
			response.setData(ResultPageUtil.resultPage(new PageInfo<Map<String, Object>>(lists), lists));
			return response;
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseMessage.CODE_400.messageToProtocol(response);
		}
	}

	@Override
	public ResponseProtocol findSignList(LeaveDutyRequestProtocol leaveDutyRequestProtocol) {
		ResponseProtocol response = protocolSelector.choose(leaveDutyRequestProtocol);
		try {
			PageHelper.startPage(leaveDutyRequestProtocol.getPageNum(), leaveDutyRequestProtocol.getPageSize());
			List<Map<String, Object>> lists = dutyLeaveMapper.findSignList(leaveDutyRequestProtocol);
			response.setData(ResultPageUtil.resultPage(new PageInfo<Map<String, Object>>(lists), lists));
			return response;
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseMessage.CODE_400.messageToProtocol(response);
		}
	}

	@Override
	public ResponseProtocol updateSignStatusById(LeaveDutyRequestProtocol leaveDutyRequestProtocol) {
		ResponseProtocol response = protocolSelector.choose(leaveDutyRequestProtocol);
		try {
			DutyResign paramDutyResign = leaveDutyRequestProtocol.getDutyResign();
			if (paramDutyResign == null) {
				return ResponseMessage.CODE_400.messageToProtocol(response);
			}
			DutyResign dutyResign = dutyResignRepository.findOne(paramDutyResign.getId());

			dutyResign.setResignStatus(Status_Public.wait);
			if (StringUtils.equals(leaveDutyRequestProtocol.getReviewStatus(), "yes")) {
				dutyResign.setResignStatus(Status_Public.yes);
			}
			if (StringUtils.equals(leaveDutyRequestProtocol.getReviewStatus(), "no")) {
				dutyResign.setResignStatus(Status_Public.no);
			}
			dutyResignRepository.save(dutyResign);
			return response;
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseMessage.CODE_400.messageToProtocol(response);
		}
	}

	@Override
	public ResponseProtocol updateSignStatusByIds(LeaveDutyRequestProtocol leaveDutyRequestProtocol) {
		ResponseProtocol response = protocolSelector.choose(leaveDutyRequestProtocol);
		try {
			String[] ids = leaveDutyRequestProtocol.getIds();
			if (ids == null) {
				return ResponseMessage.CODE_400.messageToProtocol(response);
			}
			List<String> listIds = Arrays.asList(ids);
			List<DutyResign> listDutyResign = dutyResignRepository.findAll(listIds);

			for (DutyResign dutyResign : listDutyResign) {
				dutyResign.setResignStatus(Status_Public.wait);
				if (StringUtils.equals(leaveDutyRequestProtocol.getReviewStatus(), "yes")) {
					dutyResign.setResignStatus(Status_Public.yes);
				}
				if (StringUtils.equals(leaveDutyRequestProtocol.getReviewStatus(), "no")) {
					dutyResign.setResignStatus(Status_Public.no);
				}
			}
			dutyResignRepository.save(listDutyResign);
			return response;
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseMessage.CODE_400.messageToProtocol(response);
		}
	}

	/**
	 * @author liuxincheng @Title: workRecord @Description:
	 *         TODO(我的工作记录) @param @param requestProtocol @param @param
	 *         user @param @return 设定文件 @return ResponseProtocol 返回类型 @throws
	 */
	@Override
	public ResponseProtocol workRecord(SignRequestProtocol requestProtocol, UserDTO user) {
		// TODO Auto-generated method stub
		ResponseProtocol response = protocolSelector.choose(requestProtocol);
		Map<String, Object> workRecordList = new HashMap<String, Object>();
		String status = "sign";
		int year = requestProtocol.getYear();
		int month = requestProtocol.getMonth();
		List<Duty> signList = dutyMapper.getDutyListByCodition(user.getUserId(), status, year, month);

		@SuppressWarnings("unchecked")
		Map<String, Object> warningList = (Map<String, Object>) appWarningService.handleLog(requestProtocol, user)
				.getData();

		if (!warningList.isEmpty() && signList.size() > 0) {
			workRecordList.put("signList", signList);
			workRecordList.put("fireList", warningList.get("fireList"));
			workRecordList.put("faultList", warningList.get("faultList"));
		}
		if (!workRecordList.isEmpty()) {
			ResponseMessage.CODE_200.messageToProtocol(response).setMessage("数据返回成功");
			response.setData(workRecordList);
		} else {
			ResponseMessage.CODE_400.messageToProtocol(response).setMessage("数据返回失败!");;
		}
		return response;
	}

	@Override
	public ResponseProtocol addOrUpdateDutyInfo(LeaveDutyRequestProtocol leaveDutyRequestProtocol) {
		ResponseProtocol response = protocolSelector.choose(leaveDutyRequestProtocol);
		try {
			// 获取新的班次集合
			List<Duty> dutys = leaveDutyRequestProtocol.getDutys();
			// 获取userId
			String userId = dutys.get(0).getUserId();
			String dutyMonth = leaveDutyRequestProtocol.getDutyMonth();
			String startTime = dutyMonth + "-01 00:00:00";
			String endTime = dutyMonth + "-31 23:59:59";
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			// 查找已存在班次
			leaveDutyRequestProtocol.setUserId(userId);
			leaveDutyRequestProtocol.setStartTime(sdf.parse(startTime).toString());
			leaveDutyRequestProtocol.setEndTime(sdf.parse(endTime).toString());
			
			/*leaveDutyRequestProtocol.setStartTime(startTime);
			leaveDutyRequestProtocol.setEndTime(endTime);*/
			List<Duty> listDutys = dutyMapper.getDutySheetByCondition(leaveDutyRequestProtocol);

			List<String> dataBaseDuty = new ArrayList<String>();
			for (Duty d1 : listDutys) {
				Date dutyDate = d1.getDutyDate();
				sdf = new SimpleDateFormat("yyyy-MM-dd");
				String strDutyDate = sdf.format(dutyDate);
				dataBaseDuty.add(strDutyDate);
			}
			// 获取新的班次集合中的日期
			List<String> paramDutyDate = new ArrayList<String>();
			for (Duty d1 : dutys) {
				Date dutyDate = d1.getDutyDate();
				String strDutyDate = sdf.format(dutyDate);
				paramDutyDate.add(strDutyDate);
			}
			// 删除新班次集合中不存在的班次
			List<String> result = new ArrayList<String>();
			result.clear();
			result.addAll(dataBaseDuty);
			result.retainAll(paramDutyDate);
			if (!result.isEmpty()) {
				for (Duty d1 : listDutys) {
					Date dutyDate = d1.getDutyDate();
					sdf = new SimpleDateFormat("yyyy-MM-dd");
					String strDutyDate = sdf.format(dutyDate);
					if (result.contains(strDutyDate)) {
						d1.setDutyStatus("rest");
						dutyRepository.save(d1);
					}
				}
			}
			// 保存新的班次
			result.clear();
			result.addAll(dataBaseDuty);
			dutyRepository.save(dutys);
			return response;
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseMessage.CODE_400.messageToProtocol(response);
		}
	}

	@Override
	public ResponseProtocol getDutyEmptyByUserId(LeaveDutyRequestProtocol leaveDutyRequestProtocol) {
		// TODO Auto-generated method stub
		ResponseProtocol response = protocolSelector.choose(leaveDutyRequestProtocol);
		try {
			Duty duty = leaveDutyRequestProtocol.getDuty();
			String userId = duty.getUserId();
			User user = userRepository.findOne(userId);
			if (user == null) {
				response.setCode(ResponseMessage.CODE_USERISNOTEXIST.getCode());
				response.setMessage(ResponseMessage.CODE_USERISNOTEXIST.getMessage());
				response.setIsSuccess(ResponseMessage.CODE_USERISNOTEXIST.isSuccess());
				return response;
			}
			// Date dutyDate = duty.getDutyDate();
			// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
			// String strDutyDate = sdf.format(dutyDate);
			// String strStartDuytDate = strDutyDate + "-01 00:00:00";
			// String strEndDuytDate = strDutyDate + "-31 00:00:00";
			// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd
			// HH:mm:ss");
			String dutyMonth = leaveDutyRequestProtocol.getDutyMonth();
			String strStartDuytDate = dutyMonth + "-01 00:00:00";
			String strEndDuytDate = dutyMonth + "-31 00:00:00";
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

			leaveDutyRequestProtocol.setUserId(userId);
			leaveDutyRequestProtocol.setStartTime(sdf.parse(strStartDuytDate).toString());
			leaveDutyRequestProtocol.setEndTime(sdf.parse(strEndDuytDate).toString());

			List<Duty> listDutys = dutyMapper.getDutySheetByCondition(leaveDutyRequestProtocol);

			if (listDutys == null || listDutys.isEmpty()) {
				response.setCode(ResponseMessage.CODE_200.getCode());
				response.setMessage(ResponseMessage.CODE_200.getMessage());
				response.setIsSuccess(ResponseMessage.CODE_200.isSuccess());
				return response;
			}

			response.setCode(ResponseMessage.CODE_DATAISNOTNULL.getCode());
			response.setMessage(ResponseMessage.CODE_DATAISNOTNULL.getMessage());
			response.setIsSuccess(ResponseMessage.CODE_DATAISNOTNULL.isSuccess());
			return response;
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseMessage.CODE_400.messageToProtocol(response);
		}

		// try {
		// String userName = leaveDutyRequestProtocol.getUserName();
		// List<User> users = null;
		// if (StringUtils.isNotEmpty(userName)) {
		// users = userRepository.findByName(userName);
		// }
		// if (users == null || users.isEmpty()) {
		// response.setCode(ResponseMessage.CODE_USERISNOTEXIST.getCode());
		// response.setMessage(ResponseMessage.CODE_USERISNOTEXIST.getMessage());
		// response.setIsSuccess(ResponseMessage.CODE_USERISNOTEXIST.isSuccess());
		// return response;
		// }
		// List<String> lists = new ArrayList<String>();
		// for (User user : users) {
		// String userId = user.getId();
		// // Duty duty = leaveDutyRequestProtocol.getDuty();
		// // Date dutyDate =duty.getDutyDate();
		// // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		// // String strDutyDate = sdf.format(dutyDate);
		// String dutyMonth = leaveDutyRequestProtocol.getDutyMonth();
		// String strStartDuytDate = dutyMonth + "-01 00:00:00";
		// String strEndDuytDate = dutyMonth + "-31 00:00:00";
		// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		// List<Duty> listDutys =
		// dutyRepository.findByUserIdAndDutyDateBetween(userId,
		// sdf.parse(strStartDuytDate), sdf.parse(strEndDuytDate));
		// if (listDutys == null || listDutys.isEmpty()) {
		// lists.add(userId);
		// }
		// }
		// if (!lists.isEmpty()) {
		// response.setCode(ResponseMessage.CODE_200.getCode());
		// response.setMessage(ResponseMessage.CODE_200.getMessage());
		// response.setIsSuccess(ResponseMessage.CODE_200.isSuccess());
		// response.setData(lists);
		// return response;
		// }
		// response.setCode(ResponseMessage.CODE_DATAISNOTNULL.getCode());
		// response.setMessage(ResponseMessage.CODE_DATAISNOTNULL.getMessage());
		// response.setIsSuccess(ResponseMessage.CODE_DATAISNOTNULL.isSuccess());
		//
		// return response;
		// } catch (Exception e) {
		// e.printStackTrace();
		// return ResponseMessage.CODE_400.messageToProtocol(response);
		// }

	}

	@Override
	public ResponseProtocol findDutyList(LeaveDutyRequestProtocol leaveDutyRequestProtocol) {
		ResponseProtocol response = protocolSelector.choose(leaveDutyRequestProtocol);
		try {
			List<Map<String, Object>> lists = dutyMapper.findDutyList(leaveDutyRequestProtocol);
			List<Map<String, List<Map<String, Object>>>> combineList = new ArrayList<Map<String, List<Map<String, Object>>>>();
			Map<String, List<Map<String, Object>>> combineMap = new HashMap<>();
			Set<String> userIdSet = new HashSet<>();
			for (Map<String, Object> map : lists) {
				userIdSet.add((String) map.get("userId"));
			}
			// int i=0;i<userIdSet.size();i++
			for (String userId : userIdSet) {
				combineMap.put(userId, new ArrayList<Map<String, Object>>());
				// combineList.add(combineMap);
			}
			for (Map<String, Object> map : lists) {
				List<Map<String, Object>> list = combineMap.get(map.get("userId"));
				if (list != null) {
					list.add(map);
				}
			}
			/*
			 * for( :combineList ){
			 * 
			 * List<Map<String, Object>> list =
			 * combineMap1.get(map.get("userId")); if(list!=null){
			 * list.add(map); } } }
			 */
			response.setData(combineMap);
			return response;
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseMessage.CODE_400.messageToProtocol(response);
		}
	}

	@Override
	public ResponseProtocol editDutyInfoByUserIdAnddutyMonth(LeaveDutyRequestProtocol leaveDutyRequestProtocol) {
		ResponseProtocol response = protocolSelector.choose(leaveDutyRequestProtocol);
		try {
			String userId = leaveDutyRequestProtocol.getDuty().getUserId();
			String dutyMonth = leaveDutyRequestProtocol.getDutyMonth();
			String strStartDuytDate = dutyMonth + "-01 00:00:00";
			String strEndDuytDate = dutyMonth + "-31 23:59:59";
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

			leaveDutyRequestProtocol.setUserId(userId);
			leaveDutyRequestProtocol.setStartTime(sdf.parse(strStartDuytDate).toString());
			leaveDutyRequestProtocol.setEndTime(sdf.parse(strEndDuytDate).toString());
			/*leaveDutyRequestProtocol.setStartTime(strStartDuytDate);
			leaveDutyRequestProtocol.setEndTime(strEndDuytDate);*/

			List<Duty> listDutys = dutyMapper.getDutySheetByCondition(leaveDutyRequestProtocol);

			response.setData(listDutys);

			return response;
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseMessage.CODE_400.messageToProtocol(response);
		}
	}
}
